<?php

namespace App\Library\TencentMap;

use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Common\Service\TencentMapKeysConfigService;
use App\Library\FeiShu\SendFs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;
use Ritaswc\LarkCardMessageBuilder\CardMessageBuilder;
use Ritaswc\LarkCardMessageBuilder\Tag;
use Symfony\Component\HttpFoundation\Request as RequestAlias;

class TencentMapHelp extends BaseLibrary
{

    public array $commonRequestParams = [];

    public function init()
    {
        $this->commonRequestParams = [
            "key" => TencentMapKeysConfigService::getInstance()->getRandEffectiveKey()
        ];
    }

    /**
     * 经纬度逆查询
     *
     * @param $lat
     * @param $lng
     * @return false|mixed|void
     */
    public function inverseAddressResolution($lat, $lng)
    {
        $uriPrefix = "https://apis.map.qq.com/ws/geocoder/v1/";
        return CurlResponse::getInstance(CommonService::customCurl($uriPrefix, RequestAlias::METHOD_GET,
            array_merge($this->commonRequestParams, [
                'location' => $lat . ',' . $lng,
                'get_poi'  => 0
            ])))->resolve('经纬度逆查询', function (CurlResponse $curlResponse) {
            $commonRequestParamsStr = json_encode($this->commonRequestParams, JSON_UNESCAPED_UNICODE);
            Log::info("腾讯地图请求 KEY : {$commonRequestParamsStr} |  RESPONSE : {$curlResponse->response}");
            $responseArr = json_decode($curlResponse->response, true);
            if ($responseArr) {
                switch ($responseArr["status"]) {
                    case 0:
                        return $responseArr;
                    case 121:
                        // 设置已失效key
                        TencentMapKeysConfigService::getInstance()
                                                   ->setLoseEffectiveKeys($this->commonRequestParams["key"]);
                        try {
                            // key失效触发消息推送
                            $cardMessageBuilder = (new CardMessageBuilder('[ 腾讯地图 ] 当日失效keys推送'))->template('red');
                            $instance           = TencentMapKeysConfigService::getInstance();
                            foreach ($instance->allKeys as $key) {
                                if (in_array($key, $instance->getLoseEffectiveKeys())) {
                                    $statusText = "已失效";
                                    $color      = "red";
                                } else {
                                    $statusText = "正常";
                                    $color      = "";
                                }

                                $cardMessageBuilder = $cardMessageBuilder->addElement(
                                    Tag::columnSet()
                                       ->addColumn(Tag::column()->width('weighted')->weight(1)->addElement(
                                           Tag::markdown("**key\n **{$key}"))
                                       )
                                       ->addColumn(Tag::column()->width('weighted')->weight(1)->addElement(
                                           Tag::markdown("**状态\n **<font color='{$color}'>{$statusText}</font>"))
                                       )
                                );
                            }

                            BuildFs::newRobot(SendFs::ROBOT_MAP_KEY_LOSE_EFFECTIVE, BuildFs::MSG_TYPE_CARD)
                                   ->setCardContent($cardMessageBuilder->build())
                                   ->send();
                        } catch (\Exception $exception) {
                            Log::info("[ 腾讯地图 ] 当日失效keys推送失败",
                                TencentMapKeysConfigService::getInstance()->getLoseEffectiveKeys());
                        }
                }
            }
            return false;
        });
    }

}
